package app.softtech.freechat;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import app.softtech.freechat.utils.ProjectUtils;

/**
 * 
 * @author LocDev
 * 
 */
public class ActivityLogin extends Activity implements OnClickListener {
	private static final String TAG = ActivityLogin.class.getSimpleName();

	private EditText mUsername, mPassword;
	private Button mLogin, mRegister, mForgotPassword;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);

		mUsername = (EditText) findViewById(R.id.edt_username);
		mPassword = (EditText) findViewById(R.id.edt_password);

		mLogin = (Button) findViewById(R.id.btn_login);
		mRegister = (Button) findViewById(R.id.btn_register);
		mForgotPassword = (Button) findViewById(R.id.btn_forgot_password);

		mLogin.setOnClickListener(this);
		mRegister.setOnClickListener(this);
		mForgotPassword.setOnClickListener(this);

		mUsername.setText("vanmui91");
		mPassword.setText("vanmui91");
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_login, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_login:
			if (mUsername.getText().toString().isEmpty()) {
				Log.i(TAG, "Username do not empty!");
			} else if (mPassword.getText().toString().isEmpty()) {
				Log.i(TAG, "Password do not empty");
			} else {
				new AsyncTask<Void, Void, Boolean>() {

					@Override
					protected Boolean doInBackground(Void... params) {
						if (checkLogin(mUsername.getText().toString(), mPassword.getText().toString())) {
							return true;
						}
						return false;
					}

					@Override
					protected void onPostExecute(Boolean result) {
						if (result) {
							Intent i = new Intent(ActivityLogin.this, MainActivity.class);
							startActivity(i);
							Log.i(TAG, "Login successfully!");
						} else {
							Log.i(TAG, "Login failure!");
						}
					}

				}.execute();
			}
			break;
		case R.id.btn_register:
			Intent i = new Intent(this, ActivityRegister.class);
			startActivity(i);
			break;
		case R.id.btn_forgot_password:
			Intent i2 = new Intent(this, ActivityForgotPassword.class);
			startActivity(i2);
			break;
		default:
			Log.i(TAG, "onClick - ActivityLogin - failed!");
			break;
		}
	}

	/**
	 * Function used to check the login information is correct or not
	 * @param username
	 * @param password
	 * @return true if correct - false if otherwise
	 */
	private boolean checkLogin(String username, String password) {

		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair(Constants.USERNAME, username));
		params.add(new BasicNameValuePair(Constants.PASSWORD, password));

		HttpRequest request = new HttpRequest();
		String result = request.makeServiceCall(Constants.URL_LOGIN, HttpRequest.POST, params);
		try {
			JSONObject jsonObj = new JSONObject(result);
			if (jsonObj.getString(Constants.KEY_SUCCESS) != null) {
				String check = jsonObj.getString(Constants.KEY_SUCCESS);
				if (Integer.parseInt(check) == 1) {
					JSONArray jsonArray = jsonObj.getJSONArray("data");
					JSONObject jObj = jsonArray.getJSONObject(0);
					Log.i(TAG, "user id when login succesfully: " + jObj.getString(Constants.USER_ID));
					storeUserId(jObj.getString(Constants.USER_ID));
					return true;
				} else {
					return false;
				}
			} else {
				return false;
			}
		} catch (JSONException e) {
			e.printStackTrace();
			return false;
		}
	}
	
	/**
	 * Function used to store user id 
	 * @param userId
	 */
	private void storeUserId(String userId){
		SharedPreferences prefs = ProjectUtils.getPrefs(getApplicationContext(), Constants.PROJECT_PREFS, Context.MODE_PRIVATE);
		SharedPreferences.Editor editor = prefs.edit();
		editor.putString(Constants.USER_ID, userId);
		editor.commit();
	}
}
